#!/usr/bin/python3

import requests
import sys


def get_pkgbreak_list(package_name: str) -> list:
    response = requests.get(
        "https://packages.aosc.io/revdep/{}?type=json".format(package_name))
    response.raise_for_status()
    package_info = response.json()
    pkgbreak_list = []
    pkgbreak_list = [package for group in package_info["sobreaks"]
                     for package in group if package not in pkgbreak_list]
    if package_info["sobreaks_circular"] != None:
        pkgbreak_list += package_info["sobreaks_circular"]
    if len(pkgbreak_list) == 0:
        print("Package {} has nothing to break!".format(package_name))
        exit(0)
    return pkgbreak_list


def get_package_version(package_name: str) -> str:
    response = requests.get(
        "https://packages.aosc.io/packages/{}?type=json".format(package_name))
    response.raise_for_status()
    package_info = response.json()
    package_section = "{}-{}".format(
        package_info["pkg"]["category"], package_info["pkg"]["section"])
    package_directory_name = package_info["pkg"]["directory"]
    response = requests.get(
        "https://raw.githubusercontent.com/AOSC-Dev/aosc-os-abbs/stable/{}/{}/spec".format(
            package_section, package_directory_name))
    response.raise_for_status()
    package_spec = response.text.split("\n")
    for i in package_spec:
        if i.startswith("VER="):
            package_version = i.replace("VER=", "")
            return package_version


def gen_pkgbreak_string(break_list: list) -> str:
    max_line_size = 68
    pkgbreak_list = ["{}<={}".format(
        package, get_package_version(package)) for package in break_list]
    buffer = []
    buffer2 = []
    for i in pkgbreak_list:
        buffer.append(i)
        if len(" ".join(buffer)) < max_line_size:
            buffer2.append(i)
        else:
            buffer = [i]
            buffer2.append("\\\n")
            buffer2.append(" " * 9 + " ".join(buffer))
    return "PKGBREAK=\"{}\"".format(" ".join(buffer2))


def main():
    if len(sys.argv) != 2:
        print("Usage: make-pkgbreak PACKAGENAME")
        exit(1)
    package_name = sys.argv[1]
    break_list = get_pkgbreak_list(package_name)
    print(gen_pkgbreak_string(break_list))


if __name__ == "__main__":
    main()
